import axios from "axios";
// import has = require("lodash/has");
// import merge = require("lodash/merge");
// import { resove } from "path";
import { Message } from "element-ui";
// 设置默认超时时间
const instance = axios.create({
  timeout: 6000,
});
// 设置默认请求地址
// axios.defaults.baseURL = '';
// 允许携带cookie
// axios.defaults.withCredentials = true;

// 创建axios实例，设置请求头
// const instance = axios.create({
//   haeders: {
//     "cache-Control": "no-cache", // 不使用缓存
//     Pragma: "no-cache", // 禁用缓存
//     Expires: "-1", // 设置过期时间
//   },
// })
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
// axios.defaults.headers.get['Content-Type'] = 'application/x-www-form-urlencoded';
instance.defaults.transformRequest = [
  function (data) {
    let src = "";
    for (let item in data) {
      src +=
        encodeURIComponent(item) +
        "=" +
        encodeURIComponent(data[item] === null ? "" : data[item]) +
        "&";
    }
    return src;
  },
];

function success(res) {
  const url = res.config.url;
  const urlString = url.substring(url.lastIndexOf("/") + 1);
  if (res.status === 200) {
    // console.log(res);
    if (urlString === "downloadNtFile" || urlString === "downloadJpFile") {
      return res;
    }
    if (
      res.data.code !== "200" &&
      res.data.code !== 200 &&
      res.data.status_code !== 200 &&
      urlString !== "getPersonResume" &&
      urlString !== "getUserReport" &&
      urlString !== "getUserYeJiData"
    ) {
      Message.error(res.data.status_desc);
      return Promise.reject(
        res.data.data || res.data || new Error(res.data.desc)
      );
    }
    return res.data;
  }
}

function error(res) {
  return Promise.reject(res);
}
// 请求拦截,设置统一header
instance.interceptors.request.use((config) => {
  if (process.env.NODE_ENV == "development") {
    config.headers["Authorization"] =
      "Bearer e437eac6-88e4-4cd2-84d1-497a06897d33";
    return config;
  } else {
    let token = "";
    if (localStorage.getItem("loginInfo")) {
      token = JSON.parse(localStorage.getItem("loginInfo")).token;
    }
    config.params = {
      // temp_time: new Date().getTime(), // 设置请求头携带时间戳
      ...config.params,
    };
    if (token) {
      config.headers["Authorization"] = token;
    }
    return config;
  }
});

// 响应拦截
instance.interceptors.response.use(success, error);

// 封装axio
let requestPhp = {};
requestPhp.get = function (url, params = {}) {
  return new Promise((resolve, reject) => {
    instance
      .get(url, {
        params: params,
      })
      .then((response) => {
        resolve(response);
      })
      .catch((error) => {
        reject(error);
      });
  });
};

requestPhp.post = function (url, data = {}) {
  return new Promise((resolve, reject) => {
    instance
      .post(url, data)
      .then((response) => {
        resolve(response);
      })
      .catch((error) => {
        reject(error);
      });
  });
};

export default requestPhp;
